﻿using Ay.Framework.WPF.Applications;
using Ay.Framework.WPF.Controls;
using Ay.Framework.WPF.Controls.Transitions;
using Ay.Framework.WPF.FuncFactory; 
using Ay.MvcFramework.Internal.Util;
using Microsoft.Win32;
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Threading;
using Ay.Framework.WPF;
using Demo.Common;
using Ay.MvcFramework.Config;
using TextB = Ay.Framework.WPF.TextB;

namespace Demo.Controls
{
    /// <summary>
    /// MySkinSetWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MySkinSetWindow : AyPopupWindow
    {
        public Action AfterSetSkinMethodOverride;
        private string bgDataUri = "";

        private Ay.MvcFramework.Config.DirImage currentDirImage;

        private Transition[] transition_0 = AyTransitionGetter.AyTransitionTwoWay();

        private string AYUI_BackgroundImageThumbDirectoryPath = AyuiConfig.AYUI_BackgroundImageThumbDirectoryPath;

        private string AYUI_BackgroundImageDirectoryPath = AyuiConfig.AYUI_BackgroundImageDirectoryPath;

        private ObservableCollection<TextB> ObservableCollectionTextB = new ObservableCollection<TextB>();

        private AyFuncIO ayFuncIO_0 = AyFuncFactory.GetFunc<AyFuncIO>();

        private AyFuncImage ayFuncImage_0 = AyFuncFactory.GetFunc<AyFuncImage>();

        private MySkinCommonSetWindow _mySkinCommonSetWindow;

        public MySkinSetWindow() : base(AyPopupWindowLocations.Center)
        {
            this.InitializeComponent();
            base.Loaded += new RoutedEventHandler(this.SkinSetWindow_Loaded);
            base.ShowInTaskbar = true;
            base.Icon = System.Windows.Application.Current.MainWindow.Icon;
        }

        private void btnSelectBgImage_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog()
            {
                Title = "打开",
                Filter = "位图文件 (*.bmp)|*.bmp|Jpeg 文件 (*.jpg)|*.jpg|Png 文件 (*.png)|*.png|所有 (*.bmp/*.jpg/*.png)|*.bmp;*.jpg;*.png",
                FileName = string.Empty,
                FilterIndex = 4,
                RestoreDirectory = true,
                DefaultExt = "jpg"
            };
            bool? nullable = openFileDialog.ShowDialog();
            if ((nullable.GetValueOrDefault() ? !nullable.HasValue : true))
            {
                return;
            }
            string fileName = openFileDialog.FileName;
            Path.GetFileName(fileName);
            string extension = Path.GetExtension(fileName);
            string directory = this.ayFuncIO_0.GetDirectory(string.Concat(this.AYUI_BackgroundImageDirectoryPath, AyuiConfig.Get_AYUI_DiyImageDirectoryName));
            string str = this.ayFuncIO_0.GetDirectory(string.Concat(this.AYUI_BackgroundImageThumbDirectoryPath, AyuiConfig.Get_AYUI_DiyImageDirectoryName));
            string str1 = DateTime.Now.ToString("yyMMddHHmmss");
            string str2 = string.Concat(directory, "\\", str1, extension);
            File.Copy(fileName, str2, false);
            this.ayFuncImage_0.SetConstructer(str2);
            string str3 = string.Concat(str, "\\", str1, extension);
            bool reducedImage = this.ayFuncImage_0.GetReducedImage(120, 70, str3);
            ConfigSetting.SetXmlValue("themeMode", "value", "img", "Application", false);
            if (reducedImage)
            {
                this.method_9(str2);
            }
            string str4 = str2.Replace(AyuiConfig.AYUI_BackgroundImageDirectoryPath, "");
            ConfigSetting.SetXmlValue("skinBg", "path", str4, "Application", false);
            string str5 = str3.Replace(AyuiConfig.AYUI_BackgroundImageThumbDirectoryPath, "");
            ConfigSetting.SetXmlValue("skinBg", "thumb", str5, "Application", false);
            this.method_7();
            if (this.currentDirImage != null)
            {
                this.currentDirImage.IsCurrent = false;
            }
            TextB textB = this.ObservableCollectionTextB.FirstOrDefault<TextB>((TextB x) => x.Text == AyuiConfig.AYUI_DiyImageDirectoryName);
            TextB item = new TextB()
            {
                Text = AyuiConfig.AYUI_DiyImageDirectoryName
            };
            if (textB != null)
            {
                IOrderedEnumerable<string> files =
                    from x in Directory.GetFiles(string.Concat(AyuiConfig.AYUI_BackgroundImageThumbDirectoryPath, AyuiConfig.Get_AYUI_DiyImageDirectoryName), "*.*", SearchOption.TopDirectoryOnly)
                    orderby x descending
                    select x;
                int num = 0;
                int num1 = files.Count<string>();
                int num2 = num1 / 12;
                if (num1 % 12 != 0)
                {
                    num2++;
                }
                for (int i = 0; i < num2; i++)
                {
                    List<DirImage> dirImages = new List<Ay.MvcFramework.Config.DirImage>();
                    item.ImgPath.Add(dirImages);
                }
                if (num2 > 1)
                {
                    item.NextButtonEnabled = true;
                }
                for (int j = 0; j < num1; j++)
                {
                    DirImage dirImage = new DirImage()
                    {
                        IsCurrent = false,
                        ImagePath = files.ElementAt<string>(j)
                    };
                    string str6 = dirImage.ImagePath.Replace(AyuiConfig.AYUI_BackgroundImageThumbDirectoryPath, "");
                    dirImage.RealPath = string.Concat(AyuiConfig.AYUI_BackgroundImageDirectoryPath, str6);
                    dirImage.ImageTip = "本地图片";
                    dirImage.UsePerson = "1";
                    dirImage.IsCustomed = true;
                    if (dirImage.RealPath.IndexOf(this.bgDataUri) > -1)
                    {
                        dirImage.IsCurrent = true;
                        this.currentDirImage = dirImage;
                    }
                    int num3 = num / 12;
                    num++;
                    item.ImgPath[num3].Add(dirImage);
                }
                item.CurrentItem = item.ImgPath[0];
                TextB imgPath = this.ObservableCollectionTextB[this.ObservableCollectionTextB.Count - 1];
                imgPath.ImgPath = item.ImgPath;
                imgPath.CurrentItem = item.CurrentItem;
                imgPath.PrewButtonEnabled = item.PrewButtonEnabled;
                imgPath.NextButtonEnabled = item.NextButtonEnabled;
            }
            else
            {
                List<DirImage> dirImages1 = new List<DirImage>();
                item.ImgPath.Add(dirImages1);
                item.PrewButtonEnabled = false;
                item.NextButtonEnabled = false;
                DirImage dirImage1 = new DirImage()
                {
                    IsCurrent = false,
                    ImagePath = str3,
                    RealPath = str2,
                    ImageTip = "本地图片",
                    UsePerson = "1",
                    IsCustomed = true
                };
                dirImage1.IsCurrent = true;
                this.currentDirImage = dirImage1;
                dirImages1.Add(dirImage1);
                item.CurrentItem = item.ImgPath[0];
                this.ObservableCollectionTextB.Add(item);
            }
            this.method_8();
        }

        public void GetColorData()
        {
            List<DirImage> aYUIColorsCollection = AyuiConfig.AYUI_ColorsCollection;
            Random random = new Random();
            TextB textB = new TextB()
            {
                Text = AyuiConfig.AYUI_DiyColorTabTitle
            };
            int num = 0;
            int num1 = aYUIColorsCollection.Count<DirImage>();
            int num2 = num1 / 24;
            if (num1 % 24 != 0)
            {
                num2++;
            }
            for (int i = 0; i < num2; i++)
            {
                List<DirImage> dirImages = new List<DirImage>();
                textB.ImgPath.Add(dirImages);
            }
            if (num2 > 1)
            {
                textB.NextButtonEnabled = true;
            }
            for (int j = 0; j < num1; j++)
            {
                DirImage item = aYUIColorsCollection[j];
                item.IsCurrent = false;
                item.ImageTip = "AYUI";
                int num3 = random.Next(1000, 10000);
                item.UsePerson = num3.ToString();
                item.IsCustomed = false;
                if (item.RealPath.IndexOf(this.bgDataUri) > -1)
                {
                    item.IsCurrent = true;
                    this.currentDirImage = item;
                }
                int num4 = num / 24;
                num++;
                textB.ImgPath[num4].Add(item);
            }
            textB.CurrentItem = textB.ImgPath[0];
            this.dockAyThemeCatagory.DataContext = textB;
        }

        public void GetImageData()
        {
            string[] directories = Directory.GetDirectories(this.AYUI_BackgroundImageThumbDirectoryPath);
            Random random = new Random();
            string[] strArrays = directories;
            for (int i = 0; i < (int)strArrays.Length; i++)
            {
                string str = strArrays[i];
                TextB textB = new TextB();
                string[] strArrays1 = str.Split(new char[] { '\\' });
                string str1 = strArrays1[(int)strArrays1.Length - 1];
                // textB.Text = str1.Substring(1, str1.Length - 1);
                textB.Text = str1;
                IOrderedEnumerable<string> files = Directory.GetFiles(str, "*.*", SearchOption.TopDirectoryOnly).Where<string>((string file) =>
                {
                    if (file.ToLower().EndsWith("png") || file.ToLower().EndsWith("jpg") || file.ToLower().EndsWith("bmp"))
                    {
                        return true;
                    }
                    return file.ToLower().EndsWith("jpeg");
                }).OrderByDescending<string, string>((string x) => x);
                int num = 0;
                int filesCount = files.Count<string>();
                int num2 = filesCount / 12;
                if (filesCount % 12 != 0)
                {
                    num2++;
                }
                for (int j = 0; j < num2; j++)
                {
                    List<DirImage> dirImages = new List<DirImage>();
                    textB.ImgPath.Add(dirImages);
                }
                if (num2 > 1)
                {
                    textB.NextButtonEnabled = true;
                }
                for (int k = 0; k < filesCount; k++)
                {
                    DirImage dirImage = new DirImage()
                    {
                        IsCurrent = false,
                        ImagePath = files.ElementAt<string>(k)
                    };
                    string str2 = dirImage.ImagePath.Replace(AyuiConfig.AYUI_BackgroundImageThumbDirectoryPath, "");
                    dirImage.RealPath = string.Concat(AyuiConfig.AYUI_BackgroundImageDirectoryPath, str2);
                    dirImage.ImageTip = Path.GetFileNameWithoutExtension(dirImage.ImagePath);
                    int num3 = random.Next(1000, 10000);
                    dirImage.UsePerson = num3.ToString();
                    dirImage.IsCustomed = false;
                    if (dirImage.ImagePath.IndexOf(string.Concat("\\", AyuiConfig.Get_AYUI_DiyImageDirectoryName, "\\")) > -1)
                    {
                        dirImage.IsCustomed = true;
                    }
                    if (dirImage.ImagePath.IndexOf(this.bgDataUri) > -1)
                    {
                        dirImage.IsCurrent = true;
                        this.currentDirImage = dirImage;
                    }
                    int num4 = num / 12;
                    num++;
                    textB.ImgPath[num4].Add(dirImage);
                }
                textB.CurrentItem = textB.ImgPath[0];
                this.ObservableCollectionTextB.Add(textB);
            }
            this.imgType.ItemsSource = this.ObservableCollectionTextB;
            ListTransitionSelector listTransitionSelector = new ListTransitionSelector(this.transition_0[0], this.transition_0[1], this.ObservableCollectionTextB);
            TextSearch.SetText(listTransitionSelector, TextSearch.GetText(this.transition_0[0]));
            this.tpBackgroundImage.TransitionSelector = listTransitionSelector;
        }

        private void imgType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TextB selectedItem = (sender as ListBox).SelectedItem as TextB;
            if (selectedItem != null)
            {
                selectedItem.PrewButtonEnabled = selectedItem.CurrentItemIndex > 0;
                selectedItem.NextButtonEnabled = selectedItem.CurrentItemIndex < selectedItem.ImgPath.Count - 1;
            }
        }



        private void SkinCommonSetOpen()
        {
            this._mySkinCommonSetWindow = new MySkinCommonSetWindow();
            if (AfterSetSkinMethodOverride != null)
            {
                _mySkinCommonSetWindow.AfterSetSkinMethodOverride = this.AfterSetSkinMethodOverride;
            }

            this._mySkinCommonSetWindow.ShowDialog();
        }

        private void method_11(string uri)
        {
            try
            {
                AyTransitionColor ayTransitionColor = new AyTransitionColor(uri);
                base.BgData = ayTransitionColor;
                foreach (object window in System.Windows.Application.Current.Windows)
                {
                    AyWindow ayWindow = window as AyWindow;
                    if (ayWindow == null || ayWindow.IsPinBackground)
                    {
                        continue;
                    }
                    ayTransitionColor.Radius = ayWindow.CornerRadius.TopLeft;
                    ayTransitionColor.StrokeThickness = ayWindow.BorderThickness.Top;
                    Color color = SolidColorBrushConverter.ToColor(uri);
                    HsvColor hsv = AyColorUtilities.ConvertRgbToHsv((int)color.R, (int)color.B, (int)color.G);
                    ayTransitionColor.Stroke = new SolidColorBrush(AyColorUtilities.ConvertHsvToRgb(hsv.H, hsv.S, 0.6));
                    ayWindow.BgData = ayTransitionColor;
                    ayWindow.VideoUri = null;
                }
            }
            catch (Exception exception)
            {
                Console.Write(exception.Message);
            }
        }

        private void ThemesImageSelect_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DirImage tag = (sender as Grid).Tag as DirImage;
            if (tag == null)
            {
                return;
            }
            if (!tag.IsCurrent)
            {
                tag.IsCurrent = true;
                if (this.currentDirImage != null)
                {
                    this.currentDirImage.IsCurrent = false;
                }
                this.currentDirImage = tag;
                ConfigSetting.SetXmlValue("themeMode", "value", "img", "Application", false);
                this.method_9(tag.RealPath);
                string str = tag.RealPath.Replace(AyuiConfig.AYUI_BackgroundImageDirectoryPath, "");
                ConfigSetting.SetXmlValue("skinBg", "path", str, "Application", false);
                string str1 = tag.ImagePath.Replace(AyuiConfig.AYUI_BackgroundImageThumbDirectoryPath, "");
                ConfigSetting.SetXmlValue("skinBg", "thumb", str1, "Application", false);
                this.method_8();
                this.method_7();
            }
        }

        private void ThemesColorSelect_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                DirImage tag = (sender as Border).Tag as DirImage;
                if (tag != null)
                {
                    if (!tag.IsCurrent)
                    {
                        tag.IsCurrent = true;
                        if (this.currentDirImage != null)
                        {
                            this.currentDirImage.IsCurrent = false;
                        }
                        this.currentDirImage = tag;
                        this.method_11(tag.RealPath);
                        ConfigSetting.SetXmlValue("themeMode", "value", "color", "Application", false);
                        ConfigSetting.SetXmlValue("skinColorBg", "value", tag.RealPath, "Application", false);
                        ConfigSetting.SetXmlValue("skinColorBg", "use", "1", "Application", false);
                        MyThemeManager.smethod_3(System.Windows.Application.Current, true);
                        this.method_7();
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
        }


        private void method_7()
        {
            if (this.bgDataUri.IndexOf("#") > -1 && this.bgDataUri.Length < 10)
            {
                this.bgDataUri = base.BgData.Uri;
                return;
            }
            this.bgDataUri = base.BgData.Uri.Replace("\\\\", "\\").Replace("//", "\\").Replace("////", "\\");
            if (this.bgDataUri.IndexOf(AyuiConfig.AYUI_RelativeBg_ThumbPath) > -1)
            {
                int num = this.bgDataUri.IndexOf(AyuiConfig.AYUI_RelativeBg_ThumbPath);
                this.bgDataUri = this.bgDataUri.Substring(num);
            }
        }

        private void method_8()
        {
            ConfigSetting.SetXmlValue("skinColorBg", "value", "www.ayjs.net", "Application", false);
            ConfigSetting.SetXmlValue("skinColorBg", "use", "0", "Application", false);
            MyThemeManager.smethod_3(System.Windows.Application.Current, true);
            foreach (object window in System.Windows.Application.Current.Windows)
            {
                AyWindow solidColorBrush = window as AyWindow;
                if (solidColorBrush == null || solidColorBrush.IsPinBackground)
                {
                    continue;
                }
                solidColorBrush.BgData.Stroke = new SolidColorBrush(ThemeManager.AvgColor);
            }
        }

        private void method_9(string uri)
        {
            AyTransitionPicture ayTransitionPicture = new AyTransitionPicture(uri);
            base.BgData = ayTransitionPicture;
            foreach (object window in System.Windows.Application.Current.Windows)
            {
                AyWindow ayWindow = window as AyWindow;
                if (ayWindow == null || ayWindow.IsPinBackground)
                {
                    continue;
                }
                ayTransitionPicture.Radius = ayWindow.CornerRadius.TopLeft;
                ayTransitionPicture.StrokeThickness = ayWindow.BorderThickness.Top;
                ayWindow.BgData = ayTransitionPicture;
                ayWindow.ReLoadImageBmp(uri);
                ayWindow.VideoUri = null;
            }
        }

        private void pageNext2_Click(object sender, RoutedEventArgs e)
        {
            TextB dataContext = (sender as Button).DataContext as TextB;
            if (dataContext != null)
            {
                dataContext.CurrentItemIndex = dataContext.CurrentItemIndex + 1;
                dataContext.PrewButtonEnabled = dataContext.CurrentItemIndex > 0;
                dataContext.NextButtonEnabled = dataContext.CurrentItemIndex < dataContext.ImgPath.Count - 1;
                dataContext.CurrentItem = dataContext.ImgPath[dataContext.CurrentItemIndex];
            }
        }

        private void pagePrew2_Click(object sender, RoutedEventArgs e)
        {
            TextB dataContext = (sender as Button).DataContext as TextB;
            if (dataContext != null)
            {
                dataContext.CurrentItemIndex = dataContext.CurrentItemIndex - 1;
                dataContext.PrewButtonEnabled = dataContext.CurrentItemIndex > 0;
                dataContext.NextButtonEnabled = dataContext.CurrentItemIndex < dataContext.ImgPath.Count - 1;
                dataContext.CurrentItem = dataContext.ImgPath[dataContext.CurrentItemIndex];
            }
        }

        private void SkinSetWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //base.Loaded -= new RoutedEventHandler(this.SkinSetWindow_Loaded);
            base.Dispatcher.Invoke(DispatcherPriority.Render, new ThreadStart(() =>
            {
                try
                {
                    this.method_7();
                    this.GetImageData();
                    this.loadDiv.Visibility = Visibility.Collapsed;
                    this.GetColorData();
                    this.loadDiv3.Visibility = Visibility.Collapsed;
                }
                catch (System.Exception ex)
                {
                    int iiii = 0;
                }
            }));
            // this.tb_all2.Text = AyuiConfig.AYUI_DiyColorTabTitle;//AY设计
        }



        private void tb_set3_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.SkinCommonSetOpen();
            }
            e.Handled = true;
        }


    }
}